/*
    16.Write a program in C to find the number of times a given word 'the' appears in the given string. 

    Test Data :
    Input the string : The string where the word the present more than once.

    Expected Output :

    The frequency of the word 'the' is : 3 
*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define MAX_LEN 1024
#define MAX_STR 256

char *strs[MAX_STR];

char* getstr(char *str)
{
    char ch;
    char *p = str;
    while((ch = getchar()) != '\n'){
        *p = ch;
        p++;
    }
    *p = '\0';
    return str;
}

void getword(char *str)
{
    int i = 0;
    int len = 0;
    char *p;
    while(1){
        if(isalpha(*str)){
            len++;
        }else if(len){            
            p = malloc(len + 1);
            strncpy(p, str - len, len);
            *(p + len) = '\0';
            strs[i++] = p;
            len = 0;
        }
        if(*str == '\0') 
            break;
        str++;
    }
    strs[i] = NULL;
}

void atolower(char *str)
{
    while(*str != '\0'){
        if(isupper(*str)){
            *str = *str + 32;
        }
        str++;
    }
}

int count(char *str[], char *obj)
{
    int i = 0;
    int cnt = 0;
    while(str[i]){
        if(0 == strcmp(obj, str[i])){
            cnt++;
        }
        i++;
    }
    return cnt;
}

int main(void)
{
    char *str = malloc(MAX_LEN);
    printf("Input the string : ");
    getstr(str);
    atolower(str);
    getword(str);
    printf("The frequency of word 'the' is %d", count(strs, "the"));

    return 0;
}